﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WP_GasTracker.ViewModels;
using Windows.UI.Core;
using System.Windows.Input;

namespace WP_GasTracker.Views
{
    public partial class AddEditPage : PhoneApplicationPage
    {
        private AddEditViewModel Vm
        {
            get { return DataContext as AddEditViewModel; }
        }

        public AddEditPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            InitializeViewModel();
        }

        private void InitializeViewModel()
        {
            var vm = new AddEditViewModel();
            DataContext = vm;
            string guid;
            if (NavigationContext.QueryString.TryGetValue("id", out guid))
            {
                vm.LoadById(new Guid(guid));
            }
        }

        private void DoneButton_Click(object sender, RoutedEventArgs e)
        {
            Vm.Save();
            NavigateToList();
        }

        private void List_Click(object sender, EventArgs e)
        {
            NavigateToList();
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            Vm.Delete();
            NavigateToList();
        }

        private void NavigateToList()
        {
           NavigationService.Navigate(new Uri("/Views/ListPage.xaml", UriKind.Relative));
        }

        private void DateTextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            this.DateTextBox.Focus();
        }

        private void MileageTextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }
            this.MileageTextBox.Focus();
        }
    }
}